﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Xml.Linq;
using P2PChat.Client.Data;
using System.Windows.Interop;
using System.Drawing;
using System.IO;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinMain.xaml 的交互逻辑
    /// </summary>
    public partial class WinMain : Window
    {
        public WinMain()
        {
            InitializeComponent();
            
            // 初始化全局设置
            InitGlobalSettings();

            FriendList.OnListChanged += this.OnFriendListChanged;
            log.FilePath = @"log\program.log";

        }

        void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
        }

        private void InitGlobalSettings()
        {
            // 设置服务器地址
            // 这个设置是为了在本机调试而设置
            GlobalConfig.ServerHost = "127.0.0.1";
            GlobalConfig.ServerPort = 3000;
            try
            {
                StreamReader reader = new StreamReader(@"port.config", Encoding.UTF8);
                GlobalConfig.ListeningPort = int.Parse(reader.ReadToEnd());
            }
            catch
            {
                GlobalConfig.ListeningPort = 3000;
            }
        }

        #region 私有成员
        
        // 两个窗体: "消息盒", "好友管理"

        private WinMsgBox win_MsgBox = new WinMsgBox();
        private WinFriendManage win_FriendManage = new WinFriendManage();
        
        // 日志记录器
        private P2PChat.Log.TimeStampLog log = new Log.TimeStampLog();

        // 记录分组的展开情况
        private Dictionary<string, bool> isCollapsed = new Dictionary<string, bool>();

        private System.Windows.Forms.NotifyIcon notifyIcon = null;
        
        #endregion

        private Thread showFriendsThread = null;
        // 显示好友，会根据搜索框的内容变化而刷新
        // 这个方法将会在异于窗口的线程中执行
        private void showFriends()
        {
            if (ui_Search.SearchText == null || ui_Search.SearchText == string.Empty)
            {
                // 向列表中添加小组
                panel_FriendList.Children.Clear();
                foreach (XElement group in
                    FriendList.List.Elements("Group"))
                {
                    FriendList_Group g = new FriendList_Group();
                    panel_FriendList.Children.Add(g);
                    g.SetGroupInfo(group.Attribute("name").Value,
                        group.Elements("Friend").Count()
                    );
                    g.MouseDown += new MouseButtonEventHandler(g_MouseDown);

                    foreach (XElement friend in group.Elements("Friend"))
                    {
                        FriendList_Entry entry = new FriendList_Entry();
                        panel_FriendList.Children.Add(entry);
                        entry.UserName = friend.Element("PersonalInfo").Element("Nickname").Value;
                        entry.Portrait = Images.ResourseImaging.GetPortrait(int.Parse(friend.Element("PersonalInfo").Element("Portrait").Value));
                        entry.Visibility = System.Windows.Visibility.Collapsed;
                        entry.MouseDoubleClick += new MouseButtonEventHandler(entry_MouseDoubleClick);
                        entry.UserId = Guid.Parse(friend.Element("PersonalInfo").Attribute("GUID").Value);
                    }
                }
            } // if ui_Search 为空
            else
            {
                // 对每个小组进行遍历
                foreach (XElement group in
                    FriendList.List.Element("FriendList").Elements("Group"))
                {
                    // 每个小组中查找符合搜索字符串的结果
                    foreach (XElement friend in
                        group.Elements("Friend").Where(x =>
                            x.Attribute("Name").Value.Contains(ui_Search.SearchText)))
                    {
                        FriendList_Entry entry = new FriendList_Entry();
                        entry.UserName = friend.Attribute("Name").Value;
                        // TODO 设置用户的OverridedInfo
                    }
                }
                

            }
        }

        void entry_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string Nickname = (sender as FriendList_Entry).UserName;
            Guid UserId = (sender as FriendList_Entry).UserId;

            System.Diagnostics.Debug.WriteLine(@"GUID={0}", UserId);

            try
            {
                bool jmpOut = false;
                foreach (XElement sessionXml in ChatSession.Sessions.Values)
                {
                    if (sessionXml.Element("MemberList") == null) { continue; }
                    if (sessionXml.Element("MemberList").Elements("Member").Where(x => Guid.Parse(x.Attribute("GUID").Value) == UserId).Count() > 0)
                    {
                        int key = ChatSession.Sessions.First(x => x.Value == sessionXml).Key;
                        ChatSession.ShowWindow(key);
                        jmpOut = true;
                        break;
                    }
                }
                if(!jmpOut) {
                    int key = ChatSession.NewSession();
                    ChatSession.Sessions[key] = new XElement("ChatSession");
                    ChatSession.AddMember(key, UserId);
                    ChatSession.ShowWindow(key);
                }
                
            }
            catch (Exception ex)
            {
                
            }
        }

        void g_MouseDown(object sender, MouseButtonEventArgs e)
        {
            bool isCollapse = (sender as FriendList_Group).IsCollapse = !(sender as FriendList_Group).IsCollapse;
            for (int i = panel_FriendList.Children.IndexOf(sender as FriendList_Group) + 1; i < panel_FriendList.Children.Count ; i++)
            {
                if (panel_FriendList.Children[i] is FriendList_Group)
                {
                    break;
                }
                else 
                {
                    if (isCollapse) // true : -
                    {
                        panel_FriendList.Children[i].Visibility = System.Windows.Visibility.Visible;
                    }
                    else // false : +
                    {
                        panel_FriendList.Children[i].Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
            }

        }



        private enum ShowFriendsReason {
            AppStart,
            SearchFriend,
            FriendListChanged
        }

        #region UI元素事件方法
        private void menu_Preferences_Click(object sender, RoutedEventArgs e)
        {
            new WinPreferences().ShowDialog();
            ShowBasicInfo();
        }

        private void menu_Message_Click(object sender, RoutedEventArgs e)
        {
        }

        private void menu_Contact_Click(object sender, RoutedEventArgs e)
        {
            win_FriendManage.Show();
        }

        private void menu_Exit_Click(object sender, RoutedEventArgs e)
        {
            Thread exitThread = new Thread(ToggleExit);
        }

        private void ToggleExit()
        {
            // TODO Exit Utilities.
            Application.Current.Shutdown();
        }
        #endregion

        private void ui_Search_OnTextChanged(object sender, EventArgs e)
        {
            
        }

        private void window_Load(object sender, RoutedEventArgs e)
        {
            this.Hide();

            // 登录界面
            WinStart start = new WinStart();
            start.ShowDialog();

            // 判断用户信息是否齐全, 是否需要先设定个人资料
            if (PersonalInfo.Nickname == null)
            {
                MessageBox.Show("欢迎登陆!您是第一次登录系统,请输入您的基本信息");
                WinPreferences win_Preferences = new WinPreferences();
                win_Preferences.ShowDialog();
            }
            ShowBasicInfo();

            this.Show();
            showFriends();



            notifyIcon = new System.Windows.Forms.NotifyIcon()
            {
                Icon = System.Drawing.Icon.FromHandle(Properties.Resources.ProgramIcon.GetHicon()),
                Text = "毕业设计 聊天程序",
            };
            notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
        }

        private void ShowBasicInfo()
        {
            label_Name.Content = PersonalInfo.Nickname;
            Bitmap bitmap = null;
            switch (PersonalInfo.Portrait)
            {
                case 0:
                    bitmap = Properties.Resources.Portrait_02; break;
                case 1:
                    bitmap = Properties.Resources.Portrait_01; break;
                case 2:
                    bitmap = Properties.Resources.Portrait_03; break;

            }
            if (bitmap != null)
            {
                img_Protrait.Source = Imaging.CreateBitmapSourceFromHBitmap(
                    bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }

        }

        private void btn_AddFriend_Click(object sender, RoutedEventArgs e)
        {
            new WinFriendSearch().Show();
        }


        private void OnFriendListChanged(object nullSender, EventArgs e)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    this.showFriends();
                }));
            }
            else
            {
                showFriends();
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
    }
}
